package com.zhaotianhao.controller;

import com.github.pagehelper.PageInfo;
import com.zhaotianhao.common.AjaxResult;
import com.zhaotianhao.pojo.Carts;
import com.zhaotianhao.pojo.Users;
import com.zhaotianhao.service.CartsService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @Author Z-7
 * @Date 2022/3/3
 */
@Controller
@RequestMapping("carts")
public class CartsController {
    @DubboReference
    private CartsService cartsService;
    @RequestMapping("addCarts")
    public @ResponseBody AjaxResult addCarts(Integer id, HttpSession session){
        Users login_user = (Users) session.getAttribute("LOGIN_USER");
        if(login_user == null){
            return new AjaxResult("500","请先登录",null);
        }
        Carts carts = new Carts();
        carts.setGoodsId(id);
        carts.setUserId(login_user.getId());
        Carts newCarts = cartsService.selectByUidGid(carts);
        int i = 0;
        if(newCarts != null){
            newCarts.setBuyNum(newCarts.getBuyNum() + 1);
            i += cartsService.update(newCarts);
        }else{
            i += cartsService.insert(carts);
        }
        if(i > 0){
            return new AjaxResult("200","",null);
        }
        return new AjaxResult("400","",null);
    }
    @RequestMapping("detail")
    public String detail(Carts carts,@RequestParam(defaultValue = "1")int pageNum, @RequestParam(defaultValue = "9")int pageSize, HttpSession session,Model model){
        Users login_user = (Users) session.getAttribute("LOGIN_USER");
        carts.setUserId(login_user.getId());
        PageInfo<Carts> page = cartsService.queryByPage(carts, pageNum, pageSize);
        model.addAttribute("page",page);
        return "carts/carts_list";
    }
}
